//
// Created by hsj on 2024-1-10.
// ！！！select 默认以条件触发方式工作！！！

#include <sys/time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <ctype.h>
#include <fcntl.h>

#ifdef WIN32
//windows minGW64
//inet_pton函数：_WIN32_WINNT
#ifdef _WIN32_WINNT
#undef _WIN32_WINNT
#endif
#define _WIN32_WINNT 0x0600
#include <winsock2.h>
#include <ws2tcpip.h>
//#pragma comment(lib,"ws2_32.lib")
#else
//linux  gcc
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/select.h>
#endif
#define BUF_SIZE 100
void error_handling(char *buf);
int main(int argc,char *argv[]){
    int serv_sock,clnt_sock;
    struct sockaddr_in serv_adr, clnt_adr;
    struct timeval timeout;
    /**
     *  最大值：32*8*8 = 2048
     *  最小值：32*4*8 = 1024
        typedef struct{
            long int fds_bits[32];
        }fd_set;
     */
    fd_set reads, cpy_reads;
    socklen_t adr_sz;

    int fd_max, str_len, fd_num, i;
    char buf[BUF_SIZE];
    char port[]="9999";

    serv_sock=socket(PF_INET, SOCK_STREAM, 0);
    memset(&serv_adr, 0, sizeof(serv_adr));
    serv_adr.sin_family=AF_INET;
    serv_adr.sin_addr.s_addr=htonl(INADDR_ANY);
    serv_adr.sin_port=htons(atoi(/*argv[1]*/port));

    if(bind(serv_sock, (struct sockaddr*) &serv_adr, sizeof(serv_adr))==-1)
        error_handling("bind() error" );

    if(listen(serv_sock, 128)==-1)
        error_handling("listen() error");
    printf("select serve listen on port:%s\n",port);

    FD_ZERO(&reads );
    FD_SET(serv_sock, &reads);
    fd_max=serv_sock;

    /*
         struct timeval{
           long tv_sec;//seconds
           long tv_usec;//microseconds
          };
    */

    /*
           timeout.tv_sec=5;//5 sec
           timeout.tv_usec=5000; //5 sec
     */

    while (1){
        cpy_reads=reads;
        timeout.tv_sec=5;
        timeout.tv_usec=0;

        if((fd_num=select(fd_max+1, &cpy_reads, 0, 0, &timeout))==-1)//第一个参数加+1，下标从0开始【代表遍历的数量上限】...
        {
            printf("error：%d, end\n",fd_num);
            break;//异常返回-1，结束循环
        }

        if(fd_num==0)//超时返回0，一个也没有
        {
            printf("timeout,not any client...\n");//超时返回，一个也没有
            continue;
        }

        for(i=0; i<fd_max+1; i++){
            if(FD_ISSET(i, &cpy_reads)){//FD_ISSET(int fd, fd_set * fdset) :若参数fdset指向的变量中包含文件描述符fd的信息，则返回“真”。
                if(i==serv_sock){// connection request !
                    adr_sz=sizeof(clnt_adr);
                    clnt_sock=accept(serv_sock, (struct sockaddr*)&clnt_adr, &adr_sz);
                    FD_SET(clnt_sock, &reads);
                    if(fd_max<clnt_sock)
                        fd_max=clnt_sock;
                    printf("connected a client: %d \n", clnt_sock);
                }
                else { // read message[client]
                    str_len = read(i, buf, BUF_SIZE/* - 1*/);//【这里是echo中转，接受全部，回写全部】
                    if (str_len <= 0) {// close request!
                        FD_CLR(i, &reads);
                        close(i);//关闭socket套接字
                        printf("closed client: %d \n", i);
                    }
                    else{
//                        buf[str_len]='\0';//等价于0 【这里是echo中转，接受全部，回写全部】
                        write(i, buf, str_len); //echo back
                    }
                }
            }
        }
    }
    close(serv_sock);
    return EXIT_SUCCESS;
}
void error_handling( char *message){
    fputs (message, stderr);
    fputc('\n', stderr);
    exit(1);
}